<template>
	<section>

		<el-row>
			<!--工具条-->
			<el-col :span="23" class="toolbar toolMarginTop" id="serachId">
				<el-form :inline="true" :model="filters">
					<el-button @click="marketAdd"  type="primary" size="small" style="float:left;">新增市场</el-button>
					<el-form-item style="float:right">
						<el-button type="primary" size="small" v-on:click="getList">查询</el-button>
					</el-form-item>
					<el-form-item style="float:right;">
						<el-input v-model="filters.marketName" placeholder="请输入市场名称、市场管理员" size="medium" style="width:300px"  @keyup.enter.native="searchEnterFun"></el-input>
					</el-form-item>
				</el-form>
			</el-col>
		</el-row>

		<el-col :span="23" class="toolbar titleLineSymbol">
			<!--列表-->
			<el-table :data="tableData" highlight-current-row v-loading="listLoading" @selection-change="selsChange" style="width: 100%;">
				<el-table-column type="index" label="序号" width="80">
				</el-table-column>
				<el-table-column prop="marketName" label="市场名称" width="300">
				</el-table-column>
				<el-table-column prop="marketAdmin" label="市场管理员">
				</el-table-column>
				<el-table-column prop="lxdh" label="联系电话">
				</el-table-column>
				<el-table-column prop="creater" label="创建人">
				</el-table-column>
				<el-table-column prop="createDate" label="创建时间" :formatter="formatCreateDate">
				</el-table-column>
				<el-table-column label="操作" min-width="150" align='center'>
					<template slot-scope="scope">
						<el-button type="text" size="mini" @click="marketDetails(scope.$index, scope.row)">查看</el-button>
						<el-button type="text" size="mini" @click="marketEdit(scope.$index, scope.row)">编辑</el-button>
						<el-button type="text" size="mini" @click="MarketDelete(scope.$index, scope.row)">删除</el-button>
					</template>
				</el-table-column>
			</el-table>
			<!--工具条-->
			<el-col :span="24" class="toolbar">
				<el-pagination layout="total, prev, pager, next, jumper" @current-change="handleCurrentPageChange"
								:current-page="pageNum" :page-size="pageSize" :total="total">
				</el-pagination>
			</el-col>
		</el-col>

		<!--编辑界面-->
		<Modal v-model="editFormVisible" title="市场编辑" width='50%'>
			<el-card>
			<el-form :model="editForm" label-width="120px" :rules="rules" ref="editForm">
				<el-row>
					<el-col :span="12">
						<el-form-item label="市场名称" prop="marketName">
							<el-input v-model="editForm.marketName" auto-complete="off"></el-input>
						</el-form-item>
					</el-col>
				</el-row>
				<el-row>
					<el-col :span="12">
						<el-form-item label="市场管理员" prop="marketAdmin">
							<el-select placeholder="请选择" filterable v-model="editForm.marketAdmin" @change="orgAndUserNameChange(editForm.marketAdmin)" style="width:324px">
								<el-option v-for="item in marketAdmins" :key="item.userId" :label="item.orgAndUserName" :value="item.userName">
								</el-option>
							</el-select>
						</el-form-item>
					</el-col>
				</el-row>
				<el-row>
					<el-col :span="12">
						<el-form-item label="联系电话" prop="lxdh">
							<el-input v-model="editForm.lxdh" auto-complete="off"></el-input>
						</el-form-item>
					</el-col>
				</el-row>
				<el-form-item label="发布应用需审核">
					<el-radio-group v-model="editForm.publishIsCheck">
						<el-radio class="radio" :label="0">是</el-radio>
						<el-radio class="radio" :label="1">否</el-radio>
					</el-radio-group>
				</el-form-item>
				<el-form-item label="更新应用需审核">
					<el-radio-group v-model="editForm.updateIsCheck">
						<el-radio class="radio" :label="0">是</el-radio>
						<el-radio class="radio" :label="1">否</el-radio>
					</el-radio-group>
				</el-form-item>
				<el-form-item label="覆盖范围" style="height: 200px;overflow-y: auto;" prop="fgfw">
					<el-tree :data="treeData"
								show-checkbox node-key="orgSerialNo"
								:default-expanded-keys="ShowData"
								ref="updatetree"
								highlight-current
								:props="defaultProps"
							:default-expand-all="false">
					</el-tree>
				</el-form-item>
			</el-form>
			</el-card>
			<div slot="footer" class="dialog-footer">
				<el-button @click.native="editFormVisible = false">取消</el-button>
				<el-button type="primary" @click.native="editSubmit" :loading="editLoading">提交</el-button>
			</div>
		</Modal>

		<!--新增界面-->
		<Modal v-model="addFormVisible" title="新增市场" width='50%'>
			<el-container style="height: 470px;"> 
			<el-card>
			<el-form :model="addForm" label-width="120px" :rules="rules" ref="addForm" style="height:500px">
			 <el-main style="height: 470px; border: 1px solid #eee;width:900px">
				<el-row>
					<el-col :span="12">
						<el-form-item label="市场名称" prop="marketName">
							<el-input v-model="addForm.marketName" auto-complete="off" placeholder="不超过50个汉字"></el-input>
						</el-form-item>
					</el-col>
				</el-row>
				<el-row>
					<el-col :span="12">
						<el-form-item label="市场管理员" prop="marketAdmin">
							<el-select placeholder="请选择" filterable v-model="addForm.marketAdmin" @change="orgAndUserNameChange(addForm.marketAdmin)" style="width:324px">
								<el-option v-for="item in marketAdmins" :key="item.userId" :label="item.orgAndUserName" :value="item.userName">
								</el-option>
							</el-select>
						</el-form-item>
					</el-col>
				</el-row>
				<el-row>
					<el-col :span="12">
						<el-form-item label="联系电话" prop="lxdh">
							<el-input v-model="addForm.lxdh" auto-complete="off"></el-input>
						</el-form-item>
					</el-col>
				</el-row>
				<el-form-item label="发布应用需审核">
					<el-radio-group v-model="addForm.publishIsCheck">
						<el-radio class="radio" :label="0">是</el-radio>
						<el-radio class="radio" :label="1">否</el-radio>
					</el-radio-group>
				</el-form-item>
				<el-form-item label="更新应用需审核">
					<el-radio-group v-model="addForm.updateIsCheck">
						<el-radio class="radio" :label="0">是</el-radio>
						<el-radio class="radio" :label="1">否</el-radio>
					</el-radio-group>
				</el-form-item>
				<el-form-item label="覆盖范围" style="height: 90px;overflow-y: auto;" prop="fgfw">
					<el-tree :data="treeData" show-checkbox node-key="orgSerialNo"  ref="addtree"
						highlight-current :props="defaultProps" :default-expand-all="false">
					</el-tree>
				</el-form-item>
			 </el-main>
			</el-form>
			</el-card>
			</el-container>
			<div slot="footer" class="dialog-footer">
				<el-button @click.native="addFormVisible = false">取消</el-button>
				<el-button type="primary" @click.native="addSubmit" :loading="addLoading">提交</el-button>
			</div>
		</Modal>
	</section>
</template>

<script>

	import '../../api/css/css.css';
	import Vue from 'vue';
	import iviewArea from 'iview-area';
	Vue.use(iviewArea);

	import util from '../api/util'
	//import NProgress from 'nprogress'
	import { getMarketList,addMarket,editMarket,deleteMarket,getAreaList,getPcTree,updateMarketOrg,marketOrgSearch,getOrgNameByRole } from '../../api/api';

	export default {
		data() {
			return {
				filters: {
					marketNmae: ''
				},
				tableData: [],
				treeData:[],
				ShowData:[],
                checkedTreeData:[],
                checkAll: false,
                isIndeterminate: true,
				total: 0,
				pageNum: 1,
				pageSize:10,
				listLoading: false,
				sels: [],//列表选中列

				editFormVisible: false,//编辑界面是否显示
				editLoading: false,
				rules: {
					marketName: [
						{ required: true, message: '请输入市场名称', trigger: 'blur' }
					],
					marketAdmin: [
						{ required: true, message: '请选择市场管理员', trigger: 'blur' }
					],
					lxdh: [
						{ required: true, message: '请输入联系电话', trigger: 'blur' }
					],
					fgfw: [
						{ required: true, message: '请选择覆盖范围', trigger: 'blur' }
					]
				},
				//编辑界面数据
				editForm: {
					marketName: '',
					marketAdmin: '',
					lxdh:'',
					publishIsCheck:1,
					updateIsCheck:1,
				},

				addFormVisible: false,//新增界面是否显示
				addLoading: false,
				//新增界面数据
				addForm: {
					marketName: '',
					marketAdmin: '',
					lxdh:'',
					publishIsCheck:1,
					updateIsCheck:1,
				},
				xzqhArr: [],
            	resDefault: [],
				showRes: [],
				// defaultProps: {
				// 	label: 'name',
				// 	isLeaf: 'leaf',
				// },
				defaultProps: {
                    id:'orgSerialNo',
					label: 'name',
					children: 'organizationVos',
				},
				marketCode:-1,
				marketAdmins:[]
			}
		},
		methods: {
            handleCheckAllChange(val) {
                console.log(val)
                // this.checkedTreeData = val ? this.treeData[0].organizationVos : [];
                this.checkedTreeData=[];
				if(val){
					for(var org in this.treeData[0].organizationVos){
						this.checkedTreeData.push(this.treeData[0].organizationVos[org].orgSerialNo);
					}
				}
                this.isIndeterminate = false;


            },
            handleCheckedOrgsChange(value) {
                let checkedCount = value.length;
                this.checkAll = checkedCount === this.treeData[0].organizationVos.length;
                this.isIndeterminate = checkedCount > 0 && checkedCount < this.checkedTreeData.length;
            },
			//是否启用同步显示转换
			formatIsSynchro: function (row, column) {
				return row.isSynchro == 1 ? '是' : row.isSynchro == 0 ? '否' : '未知';
			},
			formatIsEnable: function (row, column) {
				return row.isEnable == 1 ? '是' : row.isEnable == 0 ? '否' : '未知';
			},
			formatMarketClassify: function (row, column) {
				if(row.marketClassify == '1'){
					return "一级分类";
				}else if(row.marketClassify == '2'){
					return "二级分类";
				}else if(row.marketClassify == '3'){
					return "三级分类";
				}else{
					return "";
				}
			},
			formatCreateDate: function (row, column) {
				return row.createDate = (!row.createDate || row.createDate == '') ? '' : util.formatDate.format(new Date(row.createDate), 'yyyy-MM-dd hh:mm');
			},
			formatUpdateDate: function (row, column) {
				return row.updateDate = (!row.updateDate || row.updateDate == '') ? '' : util.formatDate.format(new Date(row.updateDate), 'yyyy-MM-dd hh:mm:ss');
			},
			formatAdminArea: function (row, column){
				let xzqh = JSON.parse(row.adminArea);
				let xzqhName="";
				try{xzqh.forEach(obj => {xzqhName +=obj.name;});}catch (e){console.log(e)}
				return xzqhName;
			},
			handleCurrentPageChange: function (pageNum) {// 翻页动作
                this.pageNum = pageNum;
                this.getList();// 翻页后刷新页面数据
			},
			//实现回车键搜索功能
			searchEnterFun:function(e){
				this.getList();
            },
			//获取列表
			getList() {
				let params = {
					pageNum: this.pageNum,
					pageSize: this.pageSize,
					marketName: this.filters.marketName,
					// codeList:this.$refs.tree.getCheckedKeys()
				};
				this.listLoading = true;
				//NProgress.start();
				getMarketList(params).then(function(result){
					this.tableData = result.data.list;
					this.pageNum = result.data.pageNum;
					this.pageSize = result.data.pageSize;
					this.total = result.data.total;
					this.listLoading = false;
				}.bind(this)).catch(function (error) {
					this.listLoading = false;
					console.log(error);
				}.bind(this));
			},
			getOrgNameByRole() {
				let params = {};
				getOrgNameByRole(params).then(function(result){
				    console.log("查询用户")
					console.log(result)
					this.marketAdmins = result.data.data;
				}.bind(this)).catch(function (error) {
					console.log(error);
				}.bind(this));
			},
			orgAndUserNameChange: function(value){
				let _this = this;
				this.marketAdmins.forEach(obj => {
                    if(obj.userName === value){
						 _this.addForm.lxdh = obj.lxdh;
						 _this.editForm.lxdh = obj.lxdh;
                    }
                });
			},
			//获取tree
            getPcTree() {
                let params = {};
                getPcTree(params).then(function(result){
					this.treeData = result.data;
                }.bind(this)).catch(function (error) {
                }.bind(this));
            },
			//删除
			MarketDelete: function (index, row) {
				this.$confirm('确认删除该记录吗?', '提示', {
					type: 'warning'
				}).then(() => {
					this.listLoading = true;
					//NProgress.start();
					let params = {marketCode:row.marketCode};
					deleteMarket(params).then((res) => {
						if(res.code == 'B100001'){
							this.$message({
								message: "应用市场正在使用，不允许删除！",
								type: 'info'
							});
						}else{
							//NProgress.done();
							this.$message({
								message: '删除成功',
								type: 'success'
							});
						}
						this.listLoading = false;
						this.getList();
					});
				}).catch(() => {
					this.$message({
						type: 'info',
						message: '已取消删除'
					});
				});
			},
			//显示编辑界面
			marketEdit: function (index, row) {
				// let xzqh = JSON.parse(row.adminArea);
				// let _xzqh = [];
				// try{xzqh.forEach(obj => {_xzqh.push(obj.code);});}catch(e){console.log(e)}
				// this.xzqhArr = _xzqh;
				let _this = this;
				this.marketCode = row.marketCode;
				let params = {
					marketCode: row.marketCode
				};
				marketOrgSearch(params).then(function(result){
					result.data.forEach(obj => {
						_this.ShowData.push(obj.orgSerialNo);
					});
					_this.editFormVisible = true;
					_this.editForm = Object.assign({}, row);
					setTimeout(function(){
						_this.$refs.updatetree.setCheckedNodes(result.data);
					},100);
                }.bind(this)).catch(function (error) {
                    console.log(error);
                }.bind(this));
			},
			//显示新增界面
			marketAdd: function () {
				this.addFormVisible = true;
				this.addForm = {
					marketName: '',
					marketAdmin: '',
					lxdh:'',
					publishIsCheck:1,
					updateIsCheck:1,
				};
			},
			//编辑
			editSubmit: function () {
				if(this.editForm.marketName.length > 50){
					this.$message({
						message: '市场名称不超过50个汉字',
						type: 'info'
					});
					return;
				}
				let _this = this;
				let allNodes = this.$refs.updatetree.getCheckedNodes();
				let marketOrgArr = [];
				allNodes.forEach(obj => {
                    marketOrgArr.push({"orgSerialNo":obj.orgSerialNo,"orgParentSerialNo":obj.parentSerialNo});
				});
				this.addForm.fgfw = null; // todo 作为不能填空的作用
				if(marketOrgArr.length>0){
					this.editForm.fgfw = 'true';
				}
				this.$refs.editForm.validate((valid) => {
					if (valid) {
						this.$confirm('确认提交吗？', '提示', {}).then(() => {
							this.editLoading = true;
							//NProgress.start();
							let params = Object.assign({}, this.editForm);
							params.createDate = Date.parse(new Date(params.createDate));
							if(params.updateDate != ''){
								params.updateDate = Date.parse(new Date(params.updateDate));
							}
							editMarket(params).then((res) => {
								this.editLoading = false;
								//NProgress.done();
								this.$message({
									message: '提交成功',
									type: 'success'
								});
								//保存市场与部门关系
								_this.updateMarketOrg(res.data.marketCode,marketOrgArr);
								this.$refs['editForm'].resetFields();
								this.editFormVisible = false;
								this.getList();
							});
						}).catch(() => {
							console.log("处理取消");
						});
					}
				});
			},
			//新增
			addSubmit: function () {
				if(this.addForm.marketName.length > 50){
					this.$message({
						message: '市场名称不超过50个汉字',
						type: 'info'
					});
					return;
				}
				let _this = this;
				let allNodes = this.$refs.addtree.getCheckedNodes();
				let marketOrgArr = [];
				allNodes.forEach(obj => {
                    marketOrgArr.push({"orgSerialNo":obj.orgSerialNo,"orgParentSerialNo":obj.parentSerialNo});
				});
				this.addForm.fgfw = null; // todo 作为不能填空的作用
				if(marketOrgArr.length>0){
					this.addForm.fgfw = 'true';
				}
				this.$refs.addForm.validate((valid) => {
					if (valid) {
						this.$confirm('确认提交吗？', '提示', {}).then(() => {
							this.addLoading = true;
							//NProgress.start();
							let params = Object.assign({}, this.addForm);
							//保存市场
							addMarket(params).then((res) => {
								if(res.code == 'B100001'){
									this.$message({
										message: "已存在该市场！",
										type: 'info'
									});
								}else{
									//NProgress.done();
									this.$message({
										message: '提交成功',
										type: 'success'
									});
									//保存市场与部门关系
									_this.updateMarketOrg(res.data.marketCode,marketOrgArr);
								}
								this.addLoading = false;
								this.$refs['addForm'].resetFields();
								this.addFormVisible = false;
								this.getList();
							});
						});
					}
				});
			},
			updateMarketOrg: function(marketCode,marketOrgArr){
				let params = {
                        marketCode : marketCode,
                        marketOrgs : marketOrgArr
                    }
                    updateMarketOrg(params).then((res) => {});
			},
			selsChange: function (sels) {
				this.sels = sels;
			},
			toGetList:function(){
				this.getList();
			},
			loadData(node,resolve){
				let _code = '86';
				if(node.data != null){
					_code = node.data.code;
				}
				let params ={
					code:_code,
				}
				getAreaList(params).
				then(res => {
					// if(res.data.length < 0){
					// 	res.data.map(item=>{item.leaf=true;});
					// }
					if(res.data.length > 0){
						resolve(res.data.sort(this.test));
					}
				}).catch(function (error) {
					//this.$message.warning('系统异常 ');
				});
			},
			test: function(a,b){
				return a.code-b.code
			},
			//批量删除
			batchRemove: function () {
				var ids = this.sels.map(item => item.id).toString();
				this.$confirm('确认删除选中记录吗？', '提示', {
					type: 'warning'
				}).then(() => {
					this.listLoading = true;
					//NProgress.start();
					let para = { ids: ids };
					batchRemoveUser(para).then((res) => {
						this.listLoading = false;
						//NProgress.done();
						this.$message({
							message: '删除成功',
							type: 'success'
						});
						this.getUsers();
					});
				}).catch(() => {

				});
			}
		},
		watch: {
			res1 (val) {
				this.showRes = val;
				console.log(this.showRes);
			},
			resDefault (val) {
				this.showRes = val;
			}
    	},
		mounted() {
			this.getList();
			this.getPcTree();
			this.getOrgNameByRole();
		}
	}

</script>
